﻿using B.S.RbacData.ErrorCode;
using B.S.RbacData.Read.API.Applications.Commands.RBAC;
using B.S.RbacData.Read.API.Dtos;
using MediatR;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Domain;
using Microsoft.EntityFrameworkCore;
using AutoMapper;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters.RBAC
{
    /// <summary>
    /// 获取用户信息命令处理
    /// </summary>
    public class GetUserRoleCommandHandlter : IRequestHandler<GetUserRoleCommand, ApiPaging<UserRoleDtos>>
    {
        private readonly IBaseRepository<UserModel> userRep;
        private readonly IBaseRepository<UserRoleModel> userRoleRep;
        private readonly IBaseRepository<RoleModel> roleRep;
        private readonly IMapper mapper;

        public GetUserRoleCommandHandlter(
            IBaseRepository<UserModel> userRep,
            IBaseRepository<UserRoleModel> userRoleRep,
            IBaseRepository<RoleModel> roleRep,
            IMapper mapper)
        {
            this.userRep = userRep;
            this.userRoleRep = userRoleRep;
            this.roleRep = roleRep;
            this.mapper = mapper;
        }

        public async Task<ApiPaging<UserRoleDtos>> Handle(GetUserRoleCommand request, CancellationToken cancellationToken)
        {
            // 构建基础查询，获取未删除的用户记录
            var query = userRep.GetAll()
                .AsNoTracking()
                .Where(x => !x.IsDeleted);

            // 如果传入了用户名称，则按用户名称模糊查询
            if (!string.IsNullOrEmpty(request.UserName))
            {
                query = query.Where(x => x.UserName.Contains(request.UserName));
            }

            // 计算总记录数和总页数
            var totalCount = await query.CountAsync(cancellationToken);
            var totalPages = (int)Math.Ceiling(1.0 * totalCount / request.PageSize);

            // 执行分页查询，获取用户列表
            // 按ID排序并应用分页参数
            var users = await query
                .OrderBy(x => x.ID)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToListAsync(cancellationToken);

            //  获取用户对应的角色名称列表
            var userRoleDtos = new List<UserRoleDtos>();
            foreach (var user in users)
            {
                //  通过用户-角色关联表和角色表连接查询
                var roleNames = await (from ur in userRoleRep.GetAll()
                                     join r in roleRep.GetAll() on ur.RoleId equals r.ID
                                     where ur.UserId == user.ID && !r.IsDeleted
                                     select r.RoleName)
                                     .ToListAsync(cancellationToken);

                // 将角色名称用逗号拼接成字符串
                var userRoleDto = new UserRoleDtos
                {
                    ID = user.ID,
                    UserName = user.UserName,
                    Password = user.Password,
                    RoleNames = string.Join(",", roleNames),
                    CreateTime = user.CreateTime,
                    IsState = user.IsState,
                    IsDeleted = user.IsDeleted
                };

                userRoleDtos.Add(userRoleDto);
            }

            return new ApiPaging<UserRoleDtos>
            {
                code = ResultEnumCode.Ok,
                message = "获取成功",
                TotalCount = totalCount,
                PageCount = totalPages,
                PageData = userRoleDtos
            };
        }
    }
}
